import axios, { AxiosError, AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'
import router from '../router/index'

// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_API,
  timeout: 6000
})

// 请求拦截器
service.interceptors.request.use(
  function (config: any) {
    // 让每个请求携带token
    const hasToken = window.localStorage.getItem('token')
    if (hasToken) {
      config.headers.Authorization = 'Bearer ' + hasToken
    }
    return config
  },
  function (error: AxiosError) {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const res = response.data
    // 返回的 code 不为 200 时候就会被拦截
    if (res.code !== 200) {
      if (res.code === 500) {
        ElMessage({
          showClose: true,
          message: res.msg,
          type: 'error'
        })
      }
      if (res.code === 401) {
        ElMessage({
          showClose: true,
          message: res.msg,
          type: 'error'
        })
        window.localStorage.setItem('token', '')
        router.push('/login')
      }
      return res
    } else {
      return res
    }
  },
  function (error: AxiosError) {
    ElMessage({
      showClose: true,
      message: '接口请求失败',
      type: 'error'
    })
    return Promise.reject(error)
  }
)

export default service
